<template>
    <v-container fluid>
        <v-card class="elevation-10">
            <v-card-title class="d-flex align-center pa-4">
                <div class="d-flex align-center gap-2">
                    <v-btn color="primary" prepend-icon="mdi-plus" @click="handleAdd"
                        v-if="$perms('customer_student_insert')">
                        Add
                    </v-btn>

                    <v-btn color="error" variant="outlined" :disabled="!selectRows.length" @click="handleDeleteBatch"
                        icon="mdi-delete" size="small" v-if="$perms('customer_student_import')" />

                    <v-btn v-if="$perms('customer_student_export')" color="success" variant="outlined"
                        @click="handleExport" size="small" icon="mdi-download" />

                    <v-btn v-if="$perms('customer_student_export')" color="info" variant="outlined"
                        @click="handleImport" size="small" icon="mdi-upload" />
                    <v-btn v-if="$perms('customer_student_export')" color="warning" variant="outlined"
                        @click="handleDownloadTemplate" size="small" icon="mdi-file-download" />
                </div>

                <v-spacer />

                <!-- 搜索区域 -->
                <div class="d-flex align-center gap-2">
                    <v-text-field v-model="queryParams.name_LIKE" label="姓名" variant="outlined" density="compact"
                        clearable hide-details style="width: 120px;" class="mr-2" />
                    <v-select v-model="queryParams.gender_EQ" :items="dict['customer_sex']" item-title="dictName"
                        item-value="dictValue" label="性别" variant="outlined" density="compact" clearable hide-details
                        style="width: 120px;" class="mr-2" />

                    <v-btn variant="outlined" @click="resetQuery" class="mr-2">
                        <v-icon start>mdi-refresh</v-icon>
                        Reset
                    </v-btn>

                    <v-btn type="submit" color="primary" variant="flat" @click="fetchData" class="mr-2">
                        <v-icon start>mdi-magnify</v-icon>
                        Search
                    </v-btn>

                    <v-btn variant="outlined" @click="toggleMoreQuery">
                        <v-icon start>{{ showMoreQuery ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>
                        More
                    </v-btn>
                </div>
            </v-card-title>

            <!-- 更多查询条件 -->
            <v-expand-transition>
                <v-card-text v-show="showMoreQuery" class="pt-0">
                    <v-divider class="mb-4"></v-divider>
                    <v-row>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.birthDate_BEGIN" label="出生日期开始" type="date"
                                variant="outlined" density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.birthDate_END" label="出生日期结束" type="date"
                                variant="outlined" density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.school_LIKE" label="学校" variant="outlined"
                                density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.grade_EQ" :items="dict['student_grade']"
                                item-title="dictName" item-value="dictValue" label="年级" variant="outlined"
                                density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.className_EQ" label="班级" variant="outlined"
                                density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.healthInfo_LIKE" label="健康状况" variant="outlined"
                                density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.specialNeeds_LIKE" label="需求" variant="outlined"
                                density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.educationType_EQ" :items="dict['student_education_type']"
                                item-title="dictName" item-value="dictValue" label="教育类型" variant="outlined"
                                density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.status_EQ" :items="dict['student_status']"
                                item-title="dictName" item-value="dictValue" label="状态" variant="outlined"
                                density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.createTime_BEGIN" label="创建时间开始" type="date"
                                variant="outlined" density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.createTime_END" label="创建时间结束" type="date"
                                variant="outlined" density="compact" clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-text-field v-model="queryParams.createBy_EQ" label="创建者" variant="outlined"
                                density="compact" clearable hide-details />
                        </v-col>
                    </v-row>
                </v-card-text>
            </v-expand-transition>

            <!-- 数据表格 -->
            <v-data-table v-model="selectRows" :headers="headers" :items="dataList" :loading="loading"
                :items-length="total" :items-per-page="queryParams.pageSize" :page="queryParams.pageNo" show-select
                item-value="id" @update:page="handlePageChange" @update:items-per-page="handlePageSizeChange"
                @update:model-value="setSelectRows">

                <template #item.gender="{ item }">
                    <v-chip :color="getDictColor(item['gender'], 'customer_sex')" size="small" variant="flat">
                        {{ getDictLabel(item['gender'], 'customer_sex') }}
                    </v-chip>
                </template>
                <template #item.birthDate="{ item }">
                    {{ formatDate(item['birthDate']) }}
                </template>
                <template #item.grade="{ item }">
                    <v-chip :color="getDictColor(item['grade'], 'student_grade')" size="small" variant="flat">
                        {{ getDictLabel(item['grade'], 'student_grade') }}
                    </v-chip>
                </template>
                <template #item.educationType="{ item }">
                    <v-chip :color="getDictColor(item['educationType'], 'student_education_type')" size="small"
                        variant="flat">
                        {{ getDictLabel(item['educationType'], 'student_education_type') }}
                    </v-chip>
                </template>
                <template #item.status="{ item }">
                    <v-chip :color="getDictColor(item['status'], 'student_status')" size="small" variant="flat">
                        {{ getDictLabel(item['status'], 'student_status') }}
                    </v-chip>
                </template>

                <!-- 操作列 -->
                <template #item.actions="{ item }">
                    <div class="d-flex gap-1 float-right">
                        <v-btn size="small" color="primary" variant="text" icon="mdi-pencil"
                            @click="handleEdit(item)" />
                        <v-btn size="small" color="error" variant="text" icon="mdi-delete"
                            @click="handleDelete(item)" />
                    </div>
                </template>
            </v-data-table>
        </v-card>

        <!-- 编辑对话框 -->
        <CustomersStudentManagementEdit ref="editRef" @fetch-data="fetchData" />

        <!-- 文件上传对话框 -->
        <v-dialog v-model="importDialog" max-width="500px">
            <v-card>
                <v-card-title>Import Excel</v-card-title>
                <v-card-text>
                    <v-file-input v-model="uploadFile" label="Select Excel File" accept=".xlsx,.xls"
                        prepend-icon="mdi-file-excel" variant="outlined" />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn color="grey-darken-1" variant="text" @click="importDialog = false">
                        Cancel
                    </v-btn>
                    <v-btn color="primary" variant="text" @click="confirmImport">
                        Confirm
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import {
    getList,
    doDelete,
    doDeleteAll,
    doExportExcel,
    doDownloadTemplate,
    doImportExcel,
    type CustomersStudentModel,
    type CustomersStudentQueryParams,
    type ApiResponse,
    type PageResult
} from '@/api/customer/student/CustomersStudentManagementApi';
import CustomersStudentManagementEdit from './components/CustomersStudentManagementEdit.vue';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();

// 基础数据
const loading = ref(false);
const dataList = ref<CustomersStudentModel[]>([]);
const total = ref(0);
const selectRows = ref<string[]>([]);
const editRef = ref();
const importDialog = ref(false);
const uploadFile = ref<File[]>([]);
const showMoreQuery = ref(false);

// 查询参数
const queryParams = reactive<CustomersStudentQueryParams>({
    pageNo: 1,
    pageSize: 10,
    name_LIKE: undefined,
    gender_EQ: undefined,
    birthDate_BEGIN: undefined,
    birthDate_END: undefined,
    school_LIKE: undefined,
    grade_EQ: undefined,
    className_EQ: undefined,
    healthInfo_LIKE: undefined,
    specialNeeds_LIKE: undefined,
    educationType_EQ: undefined,
    status_EQ: undefined,
    createTime_BEGIN: undefined,
    createTime_END: undefined,
    createBy_EQ: undefined,
});

// 字典数据
const dict = reactive({
    'customer_sex': [] as any[],
    'student_grade': [] as any[],
    'student_education_type': [] as any[],
    'student_status': [] as any[],
});

// 表格列定义
const headers = computed(() => [
    {
        title: '姓名',
        key: 'name',
        sortable: false,
    },
    {
        title: '性别',
        key: 'gender',
        sortable: false,
    },
    {
        title: '出生日期',
        key: 'birthDate',
        sortable: false,
    },
    {
        title: '学校',
        key: 'school',
        sortable: false,
    },
    {
        title: '年级',
        key: 'grade',
        sortable: false,
    },
    {
        title: '班级',
        key: 'className',
        sortable: false,
    },
    {
        title: '健康状况',
        key: 'healthInfo',
        sortable: false,
    },
    {
        title: '需求',
        key: 'specialNeeds',
        sortable: false,
    },
    {
        title: '教育类型',
        key: 'educationType',
        sortable: false,
    },
    {
        title: '头像',
        key: 'avatar',
        sortable: false,
    },
    {
        title: '状态',
        key: 'status',
        sortable: false,
    },
    {
        title: '创建时间',
        key: 'createTime',
        sortable: false,
    },
    {
        title: '创建者',
        key: 'createBy',
        sortable: false,
    },
    {
        title: 'Actions',
        key: 'actions',
        sortable: false,
        width: 120,
    },
]);

// 获取数据
async function fetchData() {
    loading.value = true;
    try {
        const { data }: ApiResponse<PageResult<CustomersStudentModel>> = await getList(queryParams);
        if (data) {
            dataList.value = data.rows || [];
            total.value = data.total || 0;
        }
    } catch (error) {
        console.error('Failed to fetch data:', error);
        showError('Failed to fetch data');
    } finally {
        loading.value = false;
    }
}

// 重置查询
function resetQuery() {
    Object.assign(queryParams, {
        pageNo: 1,
        pageSize: 10,
        name_LIKE: undefined,
        gender_EQ: undefined,
        birthDate_BEGIN: undefined,
        birthDate_END: undefined,
        school_LIKE: undefined,
        grade_EQ: undefined,
        className_EQ: undefined,
        healthInfo_LIKE: undefined,
        specialNeeds_LIKE: undefined,
        educationType_EQ: undefined,
        status_EQ: undefined,
        createTime_BEGIN: undefined,
        createTime_END: undefined,
        createBy_EQ: undefined,
    });
    fetchData();
}

// 切换更多查询
function toggleMoreQuery() {
    showMoreQuery.value = !showMoreQuery.value;
}

// 分页处理
function handlePageChange(page: number) {
    queryParams.pageNo = page;
    fetchData();
}

function handlePageSizeChange(size: number) {
    queryParams.pageSize = size;
    queryParams.pageNo = 1;
    fetchData();
}

// 选择处理
function setSelectRows(selected: string[]) {
    selectRows.value = selected;
}

// 新增
function handleAdd() {
    editRef.value?.showEdit();
}

// 编辑
function handleEdit(row: CustomersStudentModel) {
    editRef.value?.showEdit(row);
}

// 删除
async function handleDelete(row: CustomersStudentModel) {
    if (!confirm(`Are you sure to delete this record?`)) return;

    try {
        const { msg } = await doDelete({ id: row.id! });
        showSuccess(msg || 'Delete successful');
        fetchData();
    } catch (error) {
        console.error('Delete failed:', error);
        showError('Delete failed');
    }
}

// 批量删除
async function handleDeleteBatch() {
    if (!selectRows.value.length) {
        showError('Please select the data to delete');
        return;
    }

    if (!confirm(`Are you sure to delete the selected ${selectRows.value.length} records?`)) return;

    try {
        const { msg } = await doDeleteAll({ ids: selectRows.value.join(',') });
        showSuccess(msg || 'Batch delete successful');
        selectRows.value = [];
        fetchData();
    } catch (error) {
        console.error('Batch delete failed:', error);
        showError('Batch delete failed');
    }
}

// 导出Excel
async function handleExport() {
    try {
        await doExportExcel(queryParams);
        showSuccess('Export successful');
    } catch (error) {
        console.error('Export failed:', error);
        showError('Export failed');
    }
}

// 下载模板
async function handleDownloadTemplate() {
    try {
        await doDownloadTemplate();
        showSuccess('Download successful');
    } catch (error) {
        console.error('Download template failed:', error);
        showError('Download template failed');
    }
}

// 导入Excel
function handleImport() {
    importDialog.value = true;
    uploadFile.value = [];
}

async function confirmImport() {
    if (!uploadFile.value.length) {
        showError('Please select the file to upload');
        return;
    }

    const formData = new FormData();
    formData.append('file', uploadFile.value[0]);

    try {
        const response = await doImportExcel(formData);
        showSuccess(response.data?.msg || 'Import successful');
        importDialog.value = false;
        fetchData();
    } catch (error) {
        console.error('Import failed:', error);
        showError('Import failed');
    }
}

// 字典相关方法
function getDictLabel(value: any, dictType: string): string {
    const dictList = dict[dictType as keyof typeof dict] as any[];
    const item = dictList?.find(item => item.dictValue === value);
    return item?.dictName || value;
}

function getDictColor(value: any, dictType: string): string {
    // 根据字典值返回对应颜色
    const colors = ['primary', 'success', 'warning', 'error', 'info'];
    const dictList = dict[dictType as keyof typeof dict] as any[];
    const index = dictList?.findIndex(item => item.dictValue === value) || 0;
    return colors[index % colors.length];
}

// 日期格式化
function formatDate(date: string | Date | undefined): string {
    if (!date) return '';
    const d = new Date(date);
    return d.toLocaleString('zh-CN');
}

// 初始化字典数据
function initDict() {
    dict['customer_sex'] = getDictListSync('customer_sex') || [];
    dict['student_grade'] = getDictListSync('student_grade') || [];
    dict['student_education_type'] = getDictListSync('student_education_type') || [];
    dict['student_status'] = getDictListSync('student_status') || [];
}

// 生命周期
onMounted(() => {
    initDict();
    fetchData();
});
</script>

<style lang="scss" scoped>
.gap-2 {
    gap: 8px;
}

.gap-1 {
    gap: 4px;
}
</style>